package com.ruoyi.hr.controller.hr;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.hr.domain.*;
import com.ruoyi.hr.service.*;
import com.ruoyi.system.domain.SysUser;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/jinpeng")
public class JinPengController extends BaseController {
    @Autowired
    private JinPengService jinPengService;

    @Autowired
    private CompanysService companysService;

    @Autowired
    private DepartmentsService departmentsService;

    @Autowired
    private EducationService educationService;

    @Autowired
    private WorkingService workingService;

    @Autowired
    private QualificationService qualificationService;

    @Autowired
    private LaguagesService laguages;

    @Autowired
    private EventsService eventsService;

    @Autowired
    private JobsService jobsService;

    @Autowired
    private CompanyController companyController;

    @Autowired
    private AuthorityService authorityService;


    private String prefix = "hr/emp";

    /**
     * 跳转分页页面
     */
    @GetMapping()
    public String user() {
        return prefix + "/emp";
    }

    /**
     * 获取分页数据以及数据总量
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(JUser jUser) {
        SysUser user = ShiroUtils.getSysUser();
        List<Authority> authorityList = authorityService.getAuthorityUser(user.getUserId().toString());
        int isAdmin = 0;
        if (authorityList.size() == 1) {
            if (authorityList.get(0).getIsAdmin() != null) {
                isAdmin = 1;
            }
        }
        startPage();
        List<JUser> jUsers = jinPengService.findAll(jUser, authorityList, isAdmin);
        return getDataTable(jUsers);
    }

    /**
     * 获取菜单标题
     *
     * @param eid 员工ID
     */
    @PostMapping("/findtitle")
    @ResponseBody
    public String findtitle(Long eid) {
        JUser jUser = jinPengService.findJuserOne(eid);
        return jUser.getName();
    }

    /**
     * 获取员工的教育经历
     *
     * @param eid 员工ID
     */
    @PostMapping("/EducationList")
    @ResponseBody
    public TableDataInfo EducationList(String eid) {
        List<Education> list = educationService.findEducations(Long.parseLong(eid));
        return getDataTable1(list, list.size());
    }

    /**
     * 获取员工的工作经历
     *
     * @param eid 员工ID
     */
    @PostMapping("/WorkingList")
    @ResponseBody
    public TableDataInfo WorkingList(String eid) {
        List<Working> list = workingService.findWorkings(Long.parseLong(eid));
        return getDataTable1(list, list.size());
    }

    /**
     * 获取员工的证书信息
     *
     * @param eid 员工ID
     */
    @PostMapping("/QualificationList")
    @ResponseBody
    public TableDataInfo QualificationList(String eid) {
        List<Qualification> list = qualificationService.findQualifications(Long.parseLong(eid));
        return getDataTable1(list, list.size());
    }

    /**
     * 获取员工的语言能力
     *
     * @param eid 员工ID
     */
    @PostMapping("/LanguageList")
    @ResponseBody
    public TableDataInfo LanguageList(String eid) {
        List<Laguages> list = laguages.findLaguages(Long.parseLong(eid));
        return getDataTable1(list, list.size());
    }

    /**
     * 获取员工的入职信息
     *
     * @param eid  员工ID
     * @param type 类型 Entry:入职  Becomefull:转正  change:变动   All:所有
     */
    @PostMapping("/EeventList")
    @ResponseBody
    public TableDataInfo EeventList(String eid, String type) {
        List<Events> list = null;
        if (eid == null) {
            list = eventsService.findEvents(Long.parseLong("-1"), type);
        } else {
            list = eventsService.findEvents(Long.parseLong(eid), type);
        }

        return getDataTable1(list, list.size());
    }

    /**
     * 修改
     *
     * @param eid 主键值
     */
    @GetMapping("/edit/{eid}")
    public String edit(@PathVariable("eid") Long eid, ModelMap mmap) {
        JUser jUser = jinPengService.findJuserOne(eid);

        if (jUser.getSiling() != 0) {
            //司龄向上取整
            jUser.setSiling(Math.ceil(jUser.getSiling()));
        }
        mmap.put("jUser", jUser);
        return prefix + "/edit";
    }

    /**
     * 岗位调换
     *
     * @param eid 主键值
     */
    @RequiresPermissions("jinpeng:emp:detail")
    @GetMapping("/exchange/{eid}")
    public String exchange(@PathVariable("eid") String eid, ModelMap mmap) {
        mmap.put("eid", eid);
        return prefix + "/exchange";
    }

    /**
     * 员工离职
     *
     * @param alleid     离职员工eid
     * @param effectdate 生效日期
     */
    @PostMapping("/exQuit")
    @ResponseBody
    public int exQuit(String alleid, String effectdate) {
        String arr[] = alleid.split(",");
        List<String> eidList = new ArrayList<String>();
        for (String s : arr) {
            eidList.add(s);
        }
        int verQuit = eventsService.findIsQuit(eidList);
        if (verQuit > 0) {
            return -1;
        }
        List<JUser> jUsers = jinPengService.findJuser(eidList);
        return jinPengService.insertexQuit(jUsers, effectdate);
    }

    /**
     * 删除
     *
     * @param eid 主键值
     */
    @Log(title = "员工信息删除", businessType = BusinessType.DELETE)
    @RequiresPermissions("jinpeng:remove")
    @PostMapping("/remove/{eid}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("eid") Long eid) {
        return null;
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        SysUser user = ShiroUtils.getSysUser();
        List<Ztree> ztrees;
        List<Authority> authorityList = authorityService.getAuthorityUser(user.getUserId().toString());
        int isAdmin = 0;
        if (authorityList.size() == 1) {
            if (authorityList.get(0).getIsAdmin() != null) {
                isAdmin = 1;
            }
        }
        ztrees = this.initZtree(jinPengService.findAllTree(authorityList, isAdmin));
        return ztrees;
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */

    public List<Ztree> initZtree(List<Map<String, Object>> deptList) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        Ztree ztree;
        for (Map dept : deptList) {
            ztree = new Ztree();
            ztree.setId(Long.parseLong(dept.get("id").toString()));
            ztree.setpId(Long.parseLong(dept.get("pid").toString()));
            ztree.setName(dept.get("name").toString());
            ztree.setTitle(dept.get("name").toString());
            ztree.setChecked(true); //默认全部展开
            ztrees.add(ztree);
        }
        return ztrees;
    }

    /**
     * 获取一批需改动的人员列表
     *
     * @param eid 员工id集合
     * @return 人员信息集合
     */
    @PostMapping("/exchangeEmp")
    @ResponseBody
    public TableDataInfo exchangeEmp(String eid) {
        List<String> allEid = new ArrayList<String>();
        String[] arry = eid.split(",");
        for (String s : arry) {
            allEid.add(s);
        }
        List<JUser> jUsers = jinPengService.findJuser(allEid);
        return getDataTable1(jUsers, jUsers.size());
    }

    /**
     * 调动前验证是否有过离职
     *
     * @param allEid 验证人员EID集合
     * @return 0则无 大于0则有
     */
    @PostMapping("/exchangeVer")
    @ResponseBody
    public int exchangeVer(String allEid) {
        List<String> list = new ArrayList<String>();
        String[] arr = allEid.split(",");
        for (String s : arr) {
            list.add(s);
        }
        int num = eventsService.findIsQuit(list);
        return num;
    }

    /**
     * 离职前验证是否有过调岗
     *
     * @param allEid 验证人员EID集合
     * @return 0则无 大于0则有
     */
    @PostMapping("/exQuitVer")
    @ResponseBody
    public int exQuitVer(String allEid) {
        List<String> list = new ArrayList<String>();
        String[] arr = allEid.split(",");
        for (String s : arr) {
            list.add(s);
        }
        int num = eventsService.findIsEv(list);
        return num;
    }


    /**
     * 人员岗位调动
     *
     * @param jUsers 需要改动的人员信息集合
     * @return 改动数量
     */
    @PostMapping("/exchange")
    @ResponseBody
    public int exchange(@RequestBody List<JUser> jUsers) {
        int num = 0;
        for (JUser jUser : jUsers) {
            jinPengService.updateExchange(jUser);
            jinPengService.insertChangeOrg(jUser);
            jinPengService.inserteEvent(jUser);
            num++;
        }
        return num;
    }

    /**
     * 误操作恢复岗位
     *
     * @param allEid 员工id集合
     * @return 人员信息集合
     */
    @PostMapping("/recoveryEx")
    @ResponseBody
    public int recoveryEx(String allEid) {
        List<String> Eidlist = new ArrayList<String>();
        String[] arry = allEid.split(",");
        Empchange empchange;
        int num = 0;
        //从岗位调动记录表eChangeOrg_Register获取上一个岗位数据
        for (String eid : arry) {
            empchange = jinPengService.findEmpchange(Long.valueOf(eid));
            if (empchange != null) {
                jinPengService.updaterecoveryEx(empchange);
                num++;
            }
        }
        return num;
    }

    /**
     * 获取员工数量报表数据
     *
     * @param year 年度
     * @return 数量集合
     */
    @PostMapping("/findEcData")
    @ResponseBody
    public List<String> findEcData(String year) {
        List<String> monthNum = new ArrayList<String>();
        String time = "";
        for (int i = 1; i <= 12; i++) {
            if (i < 10) {
                time = year + "-0" + i + "-";
            } else {
                time = year + "-" + i + "-";
            }
            monthNum.add(jinPengService.findYearMonthMCount(time) + "");
        }
        return monthNum;
    }


    public String getCompDepJobName(Long CompID, Long DepdID, Long jobID) {
        //分成三次拼接，1.拼接岗位 2.拼接部门 3.拼接公司
        String compName = "";//公司名称
        String depName = "";//部门名称
        String jobsName = "";//岗位名称
        String compDepJobName = "";//总名称

        //岗位模块
        List<Jobs> AllJobs = new ArrayList<Jobs>();//用于存储所有岗位
        Jobs jobs = jobsService.findJobsOne(jobID);
        AllJobs.add(jobs);
        if (jobs.getAdminID() != null) {
            do {
                jobs = jobsService.findadminJob(jobs.getAdminID().longValue());//获取所有父岗位ID
                if (jobs != null) {
                    AllJobs.add(jobs);
                }
            } while (jobs != null && jobs.getAdminID() != null);
        }
        for (int i = AllJobs.size() - 1; i >= 0; i--) {
            jobsName += AllJobs.get(i).getTitle() + "-";
        }

        //部门模块
        List<Departments> AllDep = new ArrayList<Departments>();//用于存储所有岗位
        Departments departments = departmentsService.findDepOne(DepdID);
        AllDep.add(departments);
        if (departments.getAdminID() != null) {
            do {
                departments = departmentsService.findadminDep(departments.getAdminID().longValue());//获取所有父岗位ID
                AllDep.add(departments);
            } while (departments != null && departments.getAdminID() != null);
        }
        for (int i = AllDep.size() - 1; i >= 0; i--) {
            depName += AllDep.get(i).getTitle() + "-";
        }

        //公司模块
        compDepJobName = depName + jobsName;
        return compDepJobName;
    }
}
